package concurrency;

import java.util.HashSet;
import java.util.Set;

class RobotPool {
    /**
     * Quietly prevents identical entries:
     */
    private Set<Robot> mPool = new HashSet<Robot>();

    public synchronized void add(Robot r) {
        mPool.add(r);
        notifyAll();
    }

    public synchronized void release(Robot r) {
        add(r);
    }

    public synchronized void hire(Class<? extends Robot> robotType, Assembler assembler) throws InterruptedException {
        for (Robot r : mPool) {
            if (r.getClass().equals(robotType)) {
                mPool.remove(r);
                r.assignAssembler(assembler);
                // Power it up to do the task
                r.engage();
                return;
            }
        }
        // None available
        wait();
        // Try again, recursively
        hire(robotType, assembler);
    }
}
